package cn.jilian.front.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baidu.aip.ocr.AipOcr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;

import cn.jilian.front.domain.DrivingLicense;
import cn.jilian.front.service.DrivingLicenseService;

@Service
public class DrivingLicenseServiceImpl implements DrivingLicenseService {

	 @Autowired
	 private AipOcr aipOcr;

	 private ObjectMapper objectMapper = new ObjectMapper();

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	private final static Map<String,String> METAMAP=ImmutableMap.<String, String>builder()
			.put("使用性质","useType")
			.put("所有人","owner")
			.put("发证日期","distime")
			.put("发动机号码","engineCode")
			.put("号牌号码","flapperCode")
			.put("住址","location")
			.put("品牌型号","useType")
			.put("注册日期","regTime")
			.put("车辆识别代号","identCode")
			.put("车辆类型","vehicleType")
			.build();
	    
	@Override
	public DrivingLicense handle(byte[] data) {
		 HashMap<String, String> options = new HashMap<String, String>();
		    options.put("detect_direction", "true");
		    options.put("accuracy", "normal");
		JSONObject res = aipOcr.vehicleLicense(data, options);
		return toDrivingLicense(res);
	}

	@Override
	public DrivingLicense handle(String path) {
		HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    options.put("accuracy", "normal");
	    JSONObject res = aipOcr.vehicleLicense(path, options);
	    return toDrivingLicense(res);
	}
	
	private DrivingLicense toDrivingLicense(JSONObject data) {
		JSONObject d=data.getJSONObject("words_result");
		if(d==null)return null;
		Map<String,String> rs=new HashMap<>(METAMAP.size());
		for(String key:METAMAP.keySet()) {
			if(d.has(key)) {
				JSONObject o=d.getJSONObject(key);
				if(o!=null&&o.has("words")) {
					String v=o.getString("words");
					rs.put(METAMAP.get(key), v);
				}
			}
			
		}
		return objectMapper.convertValue(rs, DrivingLicense.class);
		
	}

}
